<template>
  <div>
    <el-card class="sourcing-table-card">
      <el-row slot="header" type="flex" justify="space-between" align="middle">
        <h4>维护潜在商品验收标准</h4>
        <BtnRender :render="renderBtnsBar" />
      </el-row>
      <div>
        <Umy-table
          :loading="tableLoading"
          :data-source="baseTableData"
          :columns="tableColumns"
          :tableHeight="300"
          @handleRowInputModify="handleRowInputModify"
        />
      </div>
    </el-card>
  </div>
</template>
<script>
import UmyTable from '@/components/UmyTable';
import BtnRender from '@/components/JSXRender/BtnRender';
import { getListPageBtnsBar } from '@/utils/getBtnsRender';
import {
  getVerticalInitDataListService,
  saveVerticalDataService,
  exportVerticalDataService,
  importVerticalDataUrl,
} from '@api/commodity/temporaryPurchasingGoods/acceptanceStandard'
import {
  EDIT_TABLE_COLUMNS,
  EDIT_TABLE_CHILDREN_COLUMNS1,
  EDIT_TABLE_CHILDREN_COLUMNS2,
} from './constants'
import {
  createExcelByExport,
  generateUuid,
  isResponseSuccess
} from '@/utils/bizUtils';
import {
  getVerticalChangeValue,
  getVerticalNewColKey,
} from './utils';

export default {
  components: {
    UmyTable,
    BtnRender,
  },
  data () {
    return {
      tableLoading: false,
      baseTableData: [],
      tableColumns: [],
      btnLoading: {
        export: false, // 导出按钮loading
        submit: false, // 提交按钮loading
      }
    };
  },
  created () {
    this.initTabaleClonum();
    const skuNos = JSON.parse(localStorage.getItem('sourcing_acceptance_skuNos') ?? '[]')
    this.getTableData(skuNos);
  },
  methods: {
    // 渲染按钮操作栏
    renderBtnsBar (h) {
      const btnList = [
        {
          label: '导出',
          method: this.handleExport,
          loading: this.btnLoading.export,
          disabled: this.baseTableData.length == 0 // 没有数据时，禁用导出按钮
        },
        {
          label: '导入',
          action: importVerticalDataUrl,
          methods: { handleUploadSuccess: this.handleUploadSuccess },
          isImport: true,
          loadingFn: state => { this.tableLoading = state }
        },
        {
          label: '提交',
          method: this.handleSubmit,
          loading: this.btnLoading.submit,
          disabled: this.baseTableData.length == 0 // 没有数据时，禁用提交按钮
        },
      ]
      return getListPageBtnsBar(h, btnList)
    },
    async getTableData (skuNos) {
      const data = skuNos
      const loadingFn = state => { this.tableLoading = state }
      const res = await getVerticalInitDataListService(data, loadingFn)
      if (res) {
        this.handleFormatTableData(res.retData ?? []);
      }
    },
    initTabaleClonum () {
      this.tableColumns = _.cloneDeep(EDIT_TABLE_COLUMNS)
    },
    handleFormatTableData (tableData) {
      this.baseTableData = [];
      this.tableColumns = [];
      this.initTabaleClonum();
      tableData.forEach((element, oneIndex) => {
        // 准备一行数据的普通列
        let curRow = {
          categoryPath: element.categoryPath,
          categoryUuid: element.categoryUuid,
          spuNo: element.spuNo,
          skuNo: element.skuNo,
          productName: element.productName,
          brandName: element.brandName,
          specDetail: element.specDetail,
          checkTime: element.checkTime,
          checkFrequency: element.checkFrequency,
          detailList: element.detailList
        };
        // 新建表头。并准备一行数据的动态列
        element.detailList.forEach((item, index) => {
          this.pushItem(oneIndex, curRow, item, index);
        });
        // 将行，添加到展示列表
        this.baseTableData.push(curRow);
      });
    },
    pushItem (oneIndex, curRow, innerEle, index) {
      curRow[getVerticalNewColKey({ key: 'checkCount', index, row: innerEle })] = innerEle.checkCount;
      // 标准值
      curRow[getVerticalNewColKey({ key: 'standardValue', index, row: innerEle })] = innerEle.standardValue;
      // 上差值
      curRow[getVerticalNewColKey({ key: 'upDiffValue', index, row: innerEle })] = innerEle.upDiffValue;
      // 下差值
      curRow[getVerticalNewColKey({ key: 'downDiffValue', index, row: innerEle })] = innerEle.downDiffValue;
      // 验收方法
      curRow[getVerticalNewColKey({ key: 'checkMethod', index, row: innerEle })] = innerEle.checkMethod;
      // 1数字5个列可填，2文本3个列可填
      curRow[getVerticalNewColKey({ key: 'checkItemType', index, row: innerEle })] = innerEle.checkItemType;
      // 表头，遍历第1行的动态列时，才追加到表头
      if (oneIndex === 0) {
        const children1 = _.cloneDeep(EDIT_TABLE_CHILDREN_COLUMNS1)
        const children2 = _.cloneDeep(EDIT_TABLE_CHILDREN_COLUMNS2)
        children1.forEach(i => {
          i.key = getVerticalNewColKey({ col: i, index, row: innerEle })
        })
        children2.forEach(i => {
          i.key = getVerticalNewColKey({ col: i, index, row: innerEle })
        })
        this.tableColumns.push({
          title: innerEle.checkItemName,
          required: innerEle.isNeed === '1',
          key: innerEle.checkItemUuid,
          width: 150,
          align: 'center',
          children: innerEle.checkItemType !== '2' ? children1 : children2
        });
      }
    },
    // 格式化提交数据
    formatSubmitData () {
      let submitList = [];
      this.baseTableData.forEach((element) => {
        element.detailList.forEach((item, innerI) => {
          item.checkCount = element[getVerticalNewColKey({ key: 'checkCount', index: innerI, row: item })];
          item.standardValue = element[getVerticalNewColKey({ key: 'standardValue', index: innerI, row: item })];
          item.upDiffValue = element[getVerticalNewColKey({ key: 'upDiffValue', index: innerI, row: item })];
          item.downDiffValue = element[getVerticalNewColKey({ key: 'downDiffValue', index: innerI, row: item })];
          item.checkMethod = element[getVerticalNewColKey({ key: 'checkMethod', index: innerI, row: item })];
        });
        submitList.push(element)
      });
      return submitList;
    },
    // 提交
    async handleSubmit () {
      if (this.baseTableData.length == 0) {
        return this.$message.warning('提交数据不能为空')
      }
      const data = { commitList: this.formatSubmitData() }
      const loadingFn = state => { this.btnLoading.submit = state }
      const res = await saveVerticalDataService(data, loadingFn)
      if (res) {
        this.$confirm('提交成功，点击确认关闭当前页面', '提示', {
          type: 'warning',
        }).then(() => {
          window.close();
        }).catch(() => {});
      }
    },
    // 导出
    async handleExport () {
      const data = { exportList: this.formatSubmitData() }
      const loadingFn = state => { this.btnLoading.export = state }
      const res = await exportVerticalDataService(data, loadingFn)
      const uuid = generateUuid()
      createExcelByExport({ excelTitle: `潜在商品验收标准_${uuid}`, res })
    },
    // 导入成功
    handleUploadSuccess (res) {
      if (isResponseSuccess(res)) {
        this.handleFormatTableData(res.retData ?? [])
      }
    },
    // 行输入框修改
    handleRowInputModify ({ row, val, columnName }) {
      this.standardValChange({ row, val, columnName })
    },
    // 标准值变更逻辑
    standardValChange ({ row, val, columnName }) {
      const {
        upDiffValue,
        downDiffValue,
        upDiffKey,
        downDiffKey,
      } = getVerticalChangeValue({ row, val, columnName }) ?? {}
      if (upDiffKey) {
        row[upDiffKey] = upDiffValue
      }
      if (downDiffKey) {
        row[downDiffKey] = downDiffValue
      }
    }
  }
};
</script>
